<html>
  <head>
    <link rel="StyleSheet" href="stylesheet.css" type="text/css" />
  </head>
  <body>
<?php
error_reporting(E_ALL & ~E_STRICT);
require_once 'NonceResponse.php';
require_once 'NonceRequest.php';
require_once 'AuthorizationRequest.php';
require_once 'AuthorizationResponse.php';
require_once 'AuthenticationRequest.php';
require_once 'AuthenticationResponse.php';
require_once 'DomainName.php';
require_once 'Database.php';
require_once 'WsseAuthSoapHeader.php';

function getFilePathUsed()
{
	//My server is an amazon server. I'm able to use the server software variable to distinguish
	//it from my development environment.  This makes development faster since I don't have to be
	//careful about which files I copy to the server.
	$serverInfo = $_SERVER['SERVER_SOFTWARE'];
	if (strstr($serverInfo, 'Amazon')) {
		//the path to use on the production server
		$filePath = '/var/www/airIdentityCredentials.txt';
	} else {
		//a different path for use on the development machine (the path where THIS file resides)
		$filePath = 'airIdentityCredentials.txt';
	}
	echo $filePath;
	
}

function TestGetNonce($client, $user) {
    echo '<h2> TestGetNonce </h2>';
    //This is the tester acting as a client as 'russ'.
    try 
    {
        $db = new Database();
        $db->connect();
        $db->logEvent(__METHOD__, 51, 'enter method');
        
        $request = new NonceRequest();
        $request->UserName = $user;
        $nonce = base64_encode($db->aesEncrypt('dedc3f57-6ce1-4504-a92f-640d8d9d23c9', $user)); //the client nonce
        $request->EncryptedClientNonce = $nonce;
        echo "nonce created and added to request. User was <u>$user</u> and the nonce was: <u>$nonce</u></br>";

        echo '<br/>Client Nonce request: '; 

        preprint($request); 

        $db->logEvent(__METHOD__, 52, 'call getNonce on SOAP server');
        $response = $client->getNonce($request);
        $db->logEvent(__METHOD__, 52, 'return from getNonce on SOAP server');
        $encodedEncryptedResponse = $response->Nonce;
        $serverNonce = base64_decode($response->Nonce);
        $serverNonce = $db->aesDecrypt($serverNonce, $user);
        $serverNonce = substr($serverNonce, 36);
        echo "serverNonce received: "; 
        preprint($serverNonce);
        return $serverNonce;
    }
    catch (Exception $ee)
    {
        echo '<h2> Exception in TestGetNonce </h2>';
        echo "<pre>";
        echo $ee->getMessage() . "--<br/>";//<br/>" . var_dump($ee->getTrace());
        echo "</pre>";

    }
}

function AddSoapHeader($client, $clientUsername, $clientPassword, $callerUsername, $callerPassword)
{
	$wsseHeader = new WsseAuthSoapHeader($clientUsername, $clientPassword, $callerUsername, $callerPassword);
	$client->__setSoapHeaders(array($wsseHeader));
}
/**
 * Tests the authentication on AirIdentity by calling it with known good values
 * @param SoapClient $client
 * @param string $user 
 */
function TestAuthenticate($client, $user, $nonce) {
    echo '<h2> TestAuthenticate </h2>';
    
    $db = new Database();
    $db->connect();
    
    $salt = "someSalt";
    $clientUsername = $user;
    $callerUsername = 'wilde';

    date_default_timezone_set('UTC');
    $timeStamp =  date('cy-m-d H:i:s',time());

    $callerNonce = uniqid() . uniqid('',TRUE);
    $callerServerNonce = $nonce;
    $callerEncrypted = $db->aesEncrypt( $callerNonce . $callerServerNonce . $timeStamp . $salt, $callerUsername);
    $callerPassword =  base64_encode($callerEncrypted);

    $clientNonce = $db->getClientNonce($clientUsername);
    $clientServerNonce = $db->getNonce($clientUsername);
    $db->logEvent(__METHOD__, 22, "clientServerNonce just got $clientServerNonce by calling \$db->getNonce($clientUsername)");
    $clientEncrypted = $db->aesEncrypt( $clientNonce . $clientServerNonce . $timeStamp . $salt, $clientUsername);
    $clientPassword =  base64_encode($clientEncrypted);

    $hash = sha1($callerUsername . $callerPassword . $clientUsername . $clientPassword);
    echo '<br/><b>callerUsername:</b> ' . $callerUsername;
    echo '<br/><b>callerPassword:</b> ' . $callerPassword;
    echo '<br/><b>clientUsername:</b> ' . $clientUsername;
    echo '<br/><b>clientPassword:</b> ' . $clientPassword;
    echo '<br/><b>hash:</b> ' . sha1($clientUsername .  $clientPassword . $callerUsername . $callerPassword);
    //build the header here.
    echo '<br/>building header & sending request</br>';
    $db->logEvent(__METHOD__, 21, 'building header');
    AddSoapHeader($client, $clientUsername, $clientPassword, $callerUsername, $callerPassword);
    $db->logEvent(__METHOD__, 21, 'building authentication request ');
    $request = new AuthenticationRequest($callerUsername, $callerPassword);
    $db->logEvent(__METHOD__, 21, 'sending authentication request ');
    $result = $client->authenticate($request);  //($clientUsername, $callerUsername, $clientPassword, $callerPassword, $hash);
    $db->logEvent(__METHOD__, 21, 'returned authentication result =' . $result->isAuthenticated);
    echo '<br/> last request: ' . $client->__getLastRequest();
    echo '<br/> Authentication Result:';
    preprint($result);
    if ($result->isAuthenticated){
        echo "<div class=\"success\">Successful authentication.</div>";
    } else {
        echo "<div class=\"failure\">Failed to authenticate.</div>";
    }
}

function preprint($var)
{
	echo "<pre>"; print_r($var); echo "</pre>";
}
//-----------------------------------------------------------------------------
// Entry Point for SOAP Server Testing
//-----------------------------------------------------------------------------
try {
    ini_set('soap.wsdl_cache_enabled', 0);
    ini_set('soap.wsdl_cache_ttl', 0);
    ini_set('default_socket_timeout', 5);
    $timezone_identifier = 'UTC';
    date_default_timezone_set($timezone_identifier);
    /**
     * The next line sets the wsdl location and assumes the actual wsdl file is
     * resident in the same folder as the client.php file is currently in. This 
     * is set this way because setting it to the dynamic ?wsdl URL based on the
     * service location breaks functionality on certain platforms (Mac, possibly
     * others).
     */
    $wsdlUrl = DomainName::getUrlUpToDomainName() . '/AirIdentity/AirIdentity.wsdl';
    echo 'using this path for configuration: ';
    getFilePathUsed();
    echo '<p>soap client created ' . date("M-d H:i:s", time()) . ' based on ' .  $wsdlUrl . '</p>';
    
    $client = new SoapClient($wsdlUrl);
    /**
     * Uncomment for testing client connectivity:
    $types = ($client->__getTypes());
    preprint($types);
    echo '...The above list of types indicates the Soap Client Was Initialized';
    $serverFunctions = $client->__getFunctions();
    echo "</br>Here are the functions I could find:</br>";
    preprint($serverFunctions);;
     */
} catch (Exception $ee1) {
	echo "<h2>initial block exception</h2>";
    echo $ee1->getMessage();
}

try {
    $db = new Database();
    $db->connect();
    
    $user = 'wilde';
    
    echo '------------------------';
    $db->logEvent("try block", 69, "About to try TestGetNonce");
    $serverNonce = TestGetNonce($client, $user);
    $db->logEvent("try block", 69, "finished with TestGetNonce. Got: $serverNonce");
    TestAuthenticate($client, $user, $serverNonce);
    echo '<br/><b>......................... authentication test completed.</b>';

} catch (Exception $ee) {
    echo '<div class="failure">Exception!</div>';
    echo $ee->getTraceAsString();
    echo '<br/>' . $client->__getLastRequest() . '<br/>';
    echo '<br/>' . $client->__getLastResponse() . '<br/>';
    echo $ee->getMessage() . '<br/>';
    echo $ee->getTraceAsString();
}
?>
  </body>
</html>